package com.texas_android.app.View;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.reflect.TypeToken;
import com.texas_android.app.Appconfig.AppConfig;
import com.texas_android.app.Appconfig.AppContext;
import com.texas_android.app.Appconfig.MyApplication;
import com.texas_android.app.R;
import com.texas_android.app.View.fragment.OneFragment;
import com.texas_android.app.http.Api;
import com.texas_android.app.http.ResponseHandler;
import com.texas_android.app.http.bean.SearchResultBean;
import com.texas_android.app.http.bean.company.CompanyBean;
import com.texas_android.app.http.bean.perssion.PerssionBean;
import com.texas_android.app.http.bean.perssion.PerssionListResultBean;
import com.texas_android.app.utils.AppOperator;
import com.texas_android.app.utils.DialogHelper;
import com.texas_android.app.utils.Logger;
import com.texas_android.app.utils.dateBase.DataBaseHelper;
import com.universal_library.activity.BaseActivity;
import com.universal_library.adapter.BaseViewPagerAdapter;
import com.universal_library.weight.AppToast;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import cz.msebera.android.httpclient.Header;

import static com.universal_library.utils.DeviceUtil.getDisplayMetrics;

/**
 * 人 信息页面
 */
public class PerssonInfoActivity extends BaseActivity implements View.OnClickListener {
    @Bind(R.id.iv_turn_bakc)
    ImageView iv_turn_bakc;

    @Bind(R.id.iv_home)
    ImageView iv_home;

    @Bind(R.id.tv_tile)
    TextView tv_title;

    @Bind(R.id.tab_nav)
    TabLayout tab_nav;

    @Bind(R.id.base_viewPager)
    ViewPager base_viewPager;

    /**
     * 第一行
     */
    //姓名
    @Bind(R.id.tv_PerssonName)
    TextView tv_Name;

    //性别
    @Bind(R.id.tv_sex)
    TextView tv_sex;

    //生日
    @Bind(R.id.tv_birthday)
    TextView tv_birthday;
    /**
     * 第二行
     */
    //民族
    @Bind(R.id.tv_nation)
    TextView tv_nation;
    //籍贯
    @Bind(R.id.tv_nativePlace)
    TextView tv_nativePlace;
    //出生地
    @Bind(R.id.tv_birthPlace)
    TextView tv_birthPlace;
    /**
     * 第三行
     */
    //入党时间
    @Bind(R.id.tv_partyDate)
    TextView tv_partyDate;
    //参加工作的时间
    @Bind(R.id.tv_wokeDate)
    TextView tv_wokeDate;
    //健康状况
    @Bind(R.id.tv_healthStatus)
    TextView tv_healthStatus;

    /**
     * 第四行
     */
    //专业技术职务
    @Bind(R.id.tv_professionalDuty)
    TextView tv_professionalDuty;
    //熟悉专业\n有何特长
    @Bind(R.id.tv_professionalPoint)
    TextView tv_professionalPoint;

    /**
     * 第五行 学历
     */
    //全日制学历
    @Bind(R.id.tv_standardEducation)
    TextView tv_standardEducation;
    //全日制毕业学校
    @Bind(R.id.tv_standardSchool)
    TextView tv_standardSchool;
    //在职学历
    @Bind(R.id.tv_workEducation)
    TextView tv_workEducation;
    //在职教育毕业学校
    @Bind(R.id.tv_workEducationSchool)
    TextView tv_workEducationSchool;

    //现任职务
    @Bind(R.id.tv_nowDuty)
    TextView tv_nowDuty;
    //简历
    @Bind(R.id.tv_offer)
    TextView tv_offer;
    //交流情况
    @Bind(R.id.tv_exchange)
    TextView tv_exchange;
    //年度考核情况
    @Bind(R.id.tv_yearCheck)
    TextView tv_yearCheck;

    @Bind(R.id.iv_userIcon)
    ImageView iv_userIcon;
    private BaseViewPagerAdapter mviewPagerAdapter;
    private PerssionBean perBean;

    private int perId = 0;
    private DialogHelper.ZXQbListDialog dialog;
    private DataBaseHelper dataBaseHelper;

    @Override
    protected int getLayoutId() {
        if (getIntent() != null && getIntent().getSerializableExtra("perBean") != null) {
            perBean = (PerssionBean) getIntent().getSerializableExtra("perBean");
            perId = perBean.getPerssionNo();
        }
        return R.layout.activity_perssion;
    }

    @Override
    protected void initView() {
        AppContext.addActivity(this);
        tv_title.setText("干部基本信息表");
        mviewPagerAdapter = new BaseViewPagerAdapter(getSupportFragmentManager(), getPagers(), this);
        base_viewPager.setAdapter(mviewPagerAdapter);
        tab_nav.setupWithViewPager(base_viewPager);
        base_viewPager.setCurrentItem(0, true);
        setIndicator(this, tab_nav, 70, 70);
        dataBaseHelper = new DataBaseHelper(this);
        dataBaseHelper.openDataBase();
        try {
            dataBaseHelper.searchZyjs(perBean.getId(), perBean);
            dataBaseHelper.searchJianli(perBean.getId(), perBean);
            dataBaseHelper.searchYearCheck(perBean.getId(), perBean);
            dataBaseHelper.searchNowDuty(perBean.getId(), perBean);
            dataBaseHelper.searchXueli(perBean.getId(), perBean);
            dataBaseHelper.searchJiangcheng(perBean.getId(),perBean);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            updateView();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dataBaseHelper.close();
    }

    public BaseViewPagerAdapter.PagerInfo[] getPagers() {
        Bundle bundle = new Bundle();
        bundle.putInt("perId", perId);
        bundle.putSerializable("persion", perBean);
        return new BaseViewPagerAdapter.PagerInfo[]{
                new BaseViewPagerAdapter.PagerInfo("基本评价", OneFragment.class, bundle)
//                ,
//                new BaseViewPagerAdapter.PagerInfo("任职意向及培养方向", TwoFragment.class, bundle),
//                new BaseViewPagerAdapter.PagerInfo("干部监督", ThreeFragment.class, bundle)
        };
    }


    @Override
    protected void initData() {

    }

    private void updateView() {
        if (perBean != null) {
            tv_Name.setText(perBean.getName());
            tv_sex.setText(perBean.getSex() + "");
            tv_birthday.setText(perBean.getBirthdaty());
            tv_nation.setText(perBean.getNation());
            tv_nativePlace.setText(perBean.getNativePlace());
            tv_birthPlace.setText(perBean.getBirthplace());
            tv_partyDate.setText(perBean.getPartyDate());
            tv_wokeDate.setText(perBean.getWorkDate());
            if (!TextUtils.isEmpty(perBean.getHealthStatus()))
                tv_healthStatus.setText(perBean.getHealthStatus());
            tv_professionalDuty.setText(perBean.getProfessionalDuty());
            tv_professionalPoint.setText(perBean.getProfessionalPoint());

            tv_standardEducation.setText(perBean.getStandardEducation());
            tv_standardSchool.setText(perBean.getStandardSchool());
            tv_workEducation.setText(perBean.getWorkEducatiodn());
            tv_workEducationSchool.setText(perBean.getWorkEduSchool());

            tv_nowDuty.setText(perBean.getNowDuty());
            tv_offer.setText(perBean.getOffers());
            tv_yearCheck.setText(perBean.getYearCheck());
            tv_exchange.setText(perBean.getRewardPunishments());

            Logger.log("图片："+"http://192.168.1.2/kaptcha" + perBean.getHeadIconurl());
            Glide.with(this).load("http://192.168.1.2/kaptcha" + perBean.getHeadIconurl()).into(iv_userIcon);
        }
    }

    @OnClick({R.id.iv_home, R.id.iv_turn_bakc})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_home:
                Intent intent = new Intent(this, MainActivity.class);
                startActivity(intent);
                finish();
                break;
            case R.id.iv_turn_bakc:
                finish();
                break;
        }
    }

    /**
     * 修改 tablayout indicator 样式
     *
     * @param context
     * @param tabs
     * @param leftDip
     * @param rightDip
     */
    public static void setIndicator(Context context, TabLayout tabs, int leftDip, int rightDip) {
        Class<?> tabLayout = tabs.getClass();
        Field tabStrip = null;
        try {
            tabStrip = tabLayout.getDeclaredField("mTabStrip");
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

        tabStrip.setAccessible(true);
        LinearLayout ll_tab = null;
        try {
            ll_tab = (LinearLayout) tabStrip.get(tabs);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        int left = (int) (getDisplayMetrics(context).density * leftDip);
        int right = (int) (getDisplayMetrics(context).density * rightDip);

        for (int i = 0; i < ll_tab.getChildCount(); i++) {
            View child = ll_tab.getChildAt(i);
            child.setPadding(0, 0, 0, 0);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
            params.leftMargin = left;
            params.rightMargin = right;
            child.setLayoutParams(params);
            child.invalidate();
        }
    }

    public int voiceSearchKey(String searchText) {
        Log.i("个人页面查询结果：", searchText);
        if (searchText.contains("返回桌面") || searchText.contains("返回系统")) {
            AppContext.closeActivityAll();
            return 0;
        }
        if (searchText.contains("选择第条")) {

        }
        if (!TextUtils.isEmpty(searchText) && searchText.length() >= 2) {
            earchInfo(searchText);
        }
        return 0;
    }

    public void earchInfo(String search) {
        Api.searchInfo(searchHandler, MyApplication.aCache.getAsString(AppConfig.APP_SERVER_TOKEN), search);
    }

    private ResponseHandler searchHandler = new ResponseHandler(this, false, "查询") {
        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, final String responseString) {
            super.onSuccess(statusCode, headers, responseString);
            if (baseBean.getStatus().equals("0")) {
                if (baseBean.getType() == 1) {
                    SearchResultBean resultBean = AppOperator.createGson().fromJson(responseString, new TypeToken<SearchResultBean>() {
                    }.getType());
                    CompanyBean companyBean = resultBean.getCompanyBean().get(0);
                    //查询结果部门
                    Intent intent = new Intent(PerssonInfoActivity.this, CompanyInfoActivity.class);
                    intent.putExtra("companyBean", companyBean);
                    overridePendingTransition(R.anim.slide_in_top, R.anim.slide_in_top);
                    startActivity(intent);
                } else {
                    final PerssionListResultBean perssionListResultBeanr = AppOperator.createGson().fromJson(responseString, new TypeToken<PerssionListResultBean>() {
                    }.getType());
                    if (perssionListResultBeanr.getPerssionBean().size() > 1) {
                        List<String> mdata = new ArrayList<>();
                        List<PerssionBean> listPersion = perssionListResultBeanr.getPerssionBean();

                        for (PerssionBean bean : listPersion) {
                            String showInfo = "<font color='#404040'> 姓名：</font>" + bean.getName()
                                    + "<font color='#404040'>  年龄：</font>" + bean.getAge()
                                    + "<font color='#404040'>  部门：</font>" + bean.getDeptFullName();
                            mdata.add(showInfo);
                        }
                        if (dialog != null && dialog.isShowing()) {
                            return;
                        }
                        dialog = DialogHelper.openZxListDialog(PerssonInfoActivity.this, mdata, "请确认您要查询的信息", 06, new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                dialog.dismiss();
                                PerssionBean perssionBean = perssionListResultBeanr.getPerssionBean().get(i);
                                //结果查询的人
                                Intent intent = new Intent(PerssonInfoActivity.this, PerssonInfoActivity.class);
                                intent.putExtra("perBean", perssionBean);
                                overridePendingTransition(R.anim.slide_in_top, R.anim.slide_in_top);
                                startActivity(intent);
                            }
                        }, new DialogHelper.OnItemSelectListenter() {
                            @Override
                            public void mySelect(int dex) {
                                if (dex <= 6 && dex < perssionListResultBeanr.getPerssionBean().size()) {
                                    try {
                                        dialog.dismiss();
                                        PerssionBean perssionBean = perssionListResultBeanr.getPerssionBean().get(dex);
                                        //结果查询的人
                                        Intent intent = new Intent(PerssonInfoActivity.this, PerssonInfoActivity.class);
                                        intent.putExtra("perBean", perssionBean);
                                        overridePendingTransition(R.anim.slide_in_top, R.anim.slide_in_top);
                                        startActivity(intent);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        AppToast.showToast(PerssonInfoActivity.this, "您说的我不明白", "请手动选择");
                                    }

                                } else {
                                    AppToast.showToast(PerssonInfoActivity.this, "您说的我不明白", "请手动选择");
                                }

                            }
                        });
                    }
                }
            } else {
                AppToast.showToast(PerssonInfoActivity.this, "", baseBean.getStatusDesc());
            }
        }
    };
}
